package controllers

import (
	"com.opennews.openplatform/web_api/shared"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Sends the raw result to client with http status code OK.
// It will not wrap the response with default map structure.
func SendRawDataResponse(ctx *gin.Context, result interface{}) {
	ctx.JSON(http.StatusOK, result)
}

// Sends the result to client with http status code OK.
// With tag success = true.
// This typically used to send a customized response to client.
func SendDataResponse(ctx *gin.Context, result interface{}) {
	response := getDefaultDataResponse(result)
	ctx.JSON(http.StatusOK, response)
}

// Sends the result to client with http status code OK.
// With tag success = false.
// This typically used to send a customized error to client.
// This is NOT a http status error.
func SendUnsuccessResponse(ctx *gin.Context, result interface{}) {
	response := getDataResponse(false, result)
	ctx.JSON(http.StatusOK, response)
}

// Sends the specific http status code to client.
func SendStatusResponse(ctx *gin.Context, statusCode int) {
	ctx.Status(statusCode)
}

// Aborts current request and sends http status code and result.
// The result might be error specific info.
func AbortWithStatusData(ctx *gin.Context, statusCode int, result interface{}) {
	response := getDataResponse(false, result)
	ctx.AbortWithStatusJSON(statusCode, response)
}

// Gets the default data response which includes a key named "success" and its value is true.
// The key named "result" holds the data result.
// shared.MapData is a shortcut for map[string]interface{}.
func getDefaultDataResponse(result interface{}) shared.MapData {
	return getDataResponse(true, result)
}

// Gets the default data response which includes a key named "success" and its value is true.
// The key named "result" holds the data result.
// shared.MapData is a shortcut for map[string]interface{}.
func getDataResponse(success bool, result interface{}) shared.MapData {
	response := make(shared.MapData)

	response["success"] = success
	response["result"] = result

	return response
}
